const robot = require("robotjs");

// 辅助函数，用于创建延迟
function sleep(ms) {
  return new Promise(resolve => setTimeout(resolve, ms));
}

const gap = 19 * 60 * 1000;
async function main() {
  // 获取屏幕尺寸
  const screenSize = robot.getScreenSize();
  const screenWidth = screenSize.width;
  const screenHeight = screenSize.height;
  console.log(`屏幕分辨率: ${screenWidth}x${screenHeight}`);

  // 计算屏幕中心点
  const centerX = screenWidth / 2;
  const centerY = screenHeight / 2;

  // 设置来回移动的距离
  const moveOffset = 100;

  console.log("开始循环移动和点击... 按下 Ctrl+C 停止。");

  // 无限循环
  while (true) {
    // 移动到中心点左侧并点击
    // const leftX = centerX - moveOffset;
    // console.log(`移动到左侧: (${leftX}, ${centerY}) 并点击 ${new Date().toLocaleTimeString()}`);
    // robot.moveMouse(leftX, centerY);
    // robot.mouseClick('left');
    // await sleep(gap); // 等待1秒
    //

    // 移动到右下角
    const rightX = screenWidth - 50;
    const bottomY = 160;
    console.log(`移动到桌面: (${rightX}, ${bottomY}) 并点击 ${new Date().toLocaleTimeString()}`);
    robot.moveMouse(rightX, bottomY);
    robot.mouseClick('left');
    await sleep(2000); // 等待1秒

    // 移动到中心点右侧并点击
    const centerx = centerX + moveOffset;
    console.log(`移动到中间: (${centerx}, ${centerY}) 并点击 ${new Date().toLocaleTimeString()}`);
    robot.moveMouse(centerx, centerY);
    // robot.mouseClick();
    robot.mouseClick('left');
    await sleep(gap); // 等待1秒
  }
}

main();
let nextGap = new Date(Date.now() + gap);
// 显示距离下一个 gap 倒计时还有多久执行
function showCountdown() {
  const now = new Date();
  const countdown = nextGap - now;
  // 分钟和秒
  const minutes = Math.floor(countdown / 60000);
  const seconds = Math.floor((countdown % 60000) / 1000);
  console.log(`${minutes}分${seconds}秒 ${nextGap.toLocaleTimeString()} 距离下一个 gap 刷新 `);
  // 如果到了gap 重置 nextGap
  if (countdown < 0) {
    nextGap = new Date(Date.now() + gap);
  }
}
let gapC = 0
// 每天下午七点51自动退出程序
setInterval(() => {
  // 如果时间到了 19:52 退出程序
  const now = new Date();
  if (now.getHours() === 21 && now.getMinutes() === 25) {
    // console.log(`时间到了 ${now.toLocaleTimeString()} 退出程序`);
    // process.exit(0);
  }
  gapC++
  if(gapC % 10 === 0) {
    showCountdown()
  }
}, 1000);
